/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.operation.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.icanci.operation.entity.*;
import cn.icanci.operation.form.UserSearchForm;
import cn.icanci.operation.mapper.TicketMapper;
import cn.icanci.operation.service.TicketService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

/**
 * @author icanci
 * @date Created in 2021/04/29 22:12
 * @version 1.0
 */
@Service
public class TicketServiceImpl implements TicketService {

    @Resource
    private TicketMapper ticketMapper;

    /**
     * 批量插入
     * @param list 更新插入
     * @return 返回
     */
    @Override
    public int insertManyRow(List<Ticket> list) {
        return ticketMapper.insertManyRow(list);
    }

    /**
     * 查询
     * @param flightNumber 查询
     * @return 返回
     */
    @Override
    public int queryNumberByFlightNumber(String flightNumber) {
        return ticketMapper.queryNumberByFlightNumber(flightNumber);
    }

    /**
     * 查询
     * @param status 查询
     * @param flightNumber
     * @return 返回
     */
    @Override
    public int queryNumberByStatus(Integer status, String flightNumber) {
        return ticketMapper.queryNumberByStatus(status, flightNumber);
    }

    /**
     * 查询所有航班信息
     * @return 返回查询的结果
     */
    @Override
    public List<String> queryFlightNumberManyRow() {
        return ticketMapper.queryFlightNumberManyRow();
    }

    /**
     * 根据航班号查询一条
     * @param flightNumber 航班号
     * @return 查询一条
     */
    @Override
    public Ticket queryOneByFlightNumber(String flightNumber) {
        return ticketMapper.queryOneByFlightNumber(flightNumber);
    }

    /**
     * 根据航班号查询一条
     * @return 查询一条
     */
    @Override
    public List<Ticket> queryManyByFlightNumber() {
        List<Ticket> ticketList = Lists.newArrayList();
        List<String> list = this.queryFlightNumberManyRow();
        if (CollectionUtil.isNotEmpty(list)) {
            for (String flightNumber : list) {
                Ticket ticket = this.queryOneByFlightNumber(flightNumber);
                ticketList.add(ticket);
            }
        }
        return ticketList;
    }

    /**
     * 统计数据进行渲染图形
     * @return 渲染图形
     */
    @Override
    public List<BaseTicketDataVO> querySellOut() {
        List<BaseTicketDataVO> baseTicketDataVOS = Lists.newArrayList();
        List<String> list = this.queryFlightNumberManyRow();
        if (CollectionUtil.isNotEmpty(list)) {
            for (String flightNumber : list) {
                BaseTicketDataVO baseTicketDataVOSellOut = new BaseTicketDataVO();
                baseTicketDataVOSellOut.setIsSellOut(SellOutEnum.IS_SELL_OUT.getDesc());
                baseTicketDataVOSellOut.setFlightNumber(flightNumber);
                baseTicketDataVOSellOut.setCount(this.queryNumberByStatus(TicketStatusEnum.IS_SELL_OUT.getStatus(), flightNumber));
                baseTicketDataVOS.add(baseTicketDataVOSellOut);

                BaseTicketDataVO baseTicketDataVONotSellOut = new BaseTicketDataVO();
                baseTicketDataVONotSellOut.setIsSellOut(SellOutEnum.NOT_SELL_OUT.getDesc());
                baseTicketDataVONotSellOut.setFlightNumber(flightNumber);
                baseTicketDataVONotSellOut.setCount(this.queryNumberByStatus(TicketStatusEnum.NOT_SELL_OUT.getStatus(), flightNumber));
                baseTicketDataVOS.add(baseTicketDataVONotSellOut);
            }
        }
        return baseTicketDataVOS;
    }

    /**
     * 统计机票的详情信息
     * @param flightNumber
     * @return 返回统计分析结果
     */
    @Override
    public List<TicketDetailsVO> queryTicketDetailByFlightNumber(String flightNumber) {
        List<Ticket> ticketList = ticketMapper.queryAllByFlightNumber(flightNumber);
        List<TicketDetailsVO> ticketDetailsVOS = Lists.newArrayList();
        Map<Integer, List<Ticket>> collectOne = ticketList.stream().collect(Collectors.groupingBy(o -> o.getTicketLevel()));
        for (Map.Entry<Integer, List<Ticket>> entry : collectOne.entrySet()) {
            Integer key = entry.getKey();
            List<Ticket> value = entry.getValue();
            TicketLevelEnum[] values = TicketLevelEnum.values();
            for (TicketLevelEnum levelEnum : values) {
                if (key.intValue() == levelEnum.getLevel().intValue()) {
                    Map<Integer, List<Ticket>> collectTwo = value.stream().collect(Collectors.groupingBy(o -> o.getStatus()));
                    for (Map.Entry<Integer, List<Ticket>> listEntry : collectTwo.entrySet()) {
                        Integer keyTwo = listEntry.getKey();
                        List<Ticket> valueTwo = listEntry.getValue();
                        TicketDetailsVO ticketDetailsVO = new TicketDetailsVO();
                        if (TicketStatusEnum.NOT_SELL_OUT.getStatus().intValue() == keyTwo.intValue()) {
                            ticketDetailsVO.setType(levelEnum.getDesc());
                            ticketDetailsVO.setName(levelEnum.getDesc() + TicketStatusEnum.NOT_SELL_OUT.getDesc());
                            ticketDetailsVO.setValue(valueTwo.size());
                            ticketDetailsVOS.add(ticketDetailsVO);
                        } else if (TicketStatusEnum.IS_SELL_OUT.getStatus().intValue() == keyTwo.intValue()) {
                            ticketDetailsVO.setType(levelEnum.getDesc());
                            ticketDetailsVO.setName(levelEnum.getDesc() + TicketStatusEnum.IS_SELL_OUT.getDesc());
                            ticketDetailsVO.setValue(valueTwo.size());
                            ticketDetailsVOS.add(ticketDetailsVO);
                        }
                    }
                }
            }
        }
        return ticketDetailsVOS;
    }

    /**
     * 统计机票的详情信息
     * @param flightNumber
     * @return 返回统计分析结果
     */
    @Override
    public List<Ticket> queryAllByFlightNumber(String flightNumber) {
        return ticketMapper.queryAllByFlightNumber(flightNumber);
    }

    /**
     * 用户查询机票
     * @param userSearchForm
     * @return
     */
    @Override
    public List<Ticket> userQueryTicket(UserSearchForm userSearchForm) {
        List<Ticket> ticketList = Lists.newArrayList();
        if (null == userSearchForm) {
            return ticketList;
        }
        // 查询机票 航班
        // 1 单程 2 往返

        userSearchForm.setNow(new Date());
        if ("1".equals(userSearchForm.getTripTypeRadio())) {
            // 单程
            Date startDate = userSearchForm.getStartDate();
            if (null != startDate) {
                userSearchForm.setFirstDate(DateUtil.beginOfDay(startDate));
                userSearchForm.setSecondDate(DateUtil.endOfDay(startDate));
            }
            List<Ticket> tickets = ticketMapper.userQueryTicket(userSearchForm);
            if (CollectionUtil.isEmpty(tickets)) {
                ticketList.addAll(tickets);
            } else {
                List<Ticket> collect = tickets.stream().filter(this.distinctByKey(o -> o.getFlightNumber())).collect(Collectors.toList());
                ticketList.addAll(collect);
            }
        } else if ("2".equals(userSearchForm.getTripTypeRadio())) {
            // go
            Date startDate = userSearchForm.getStartDate();
            if (null != startDate) {
                userSearchForm.setFirstDate(DateUtil.beginOfDay(startDate));
                userSearchForm.setSecondDate(DateUtil.endOfDay(startDate));
            }
            List<Ticket> ticketGo = ticketMapper.userQueryTicket(userSearchForm);
            if (CollectionUtil.isEmpty(ticketGo)) {
                ticketList.addAll(ticketGo);
            } else {
                List<Ticket> collect = ticketGo.stream().filter(this.distinctByKey(o -> o.getFlightNumber())).collect(Collectors.toList());
                ticketList.addAll(collect);
            }
            // back

            String arriveCity = userSearchForm.getArriveCity();
            String startCity = userSearchForm.getStartCity();
            userSearchForm.setStartCity(arriveCity);
            userSearchForm.setArriveCity(startCity);
            userSearchForm.setStartDate(userSearchForm.getArriveDate());
            startDate = userSearchForm.getStartDate();
            if (null != startDate) {
                userSearchForm.setFirstDate(DateUtil.beginOfDay(startDate));
                userSearchForm.setSecondDate(DateUtil.endOfDay(startDate));
            }
            List<Ticket> ticketBack = ticketMapper.userQueryTicket(userSearchForm);
            if (CollectionUtil.isEmpty(ticketBack)) {
                ticketList.addAll(ticketBack);
            } else {
                List<Ticket> collect = ticketBack.stream().filter(this.distinctByKey(o -> o.getFlightNumber())).collect(Collectors.toList());
                ticketList.addAll(collect);
            }
        }
        return ticketList;
    }

    /**
     * 查询一条数据
     * @param id
     * @return
     */
    @Override public Ticket queryTicketDetailDataById(Long id) {
        return ticketMapper.queryTicketDetailDataById(id);
    }

    /**
     * 更新机票状态
     * @param id
     */
    @Override public void updateTicketDetailDataById(Long id) {
        Ticket ticket = this.queryTicketDetailDataById(id);
        ticket.setStatus(0);
        ticketMapper.updateTicketDetailDataById(ticket);
    }

    /**
     * 去除方法
     * @param keyExtractor
     * @param <T>
     * @return
     */
    private <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    /**
     * 得到返回的时间
     * @param date
     * @return
     */
    private List<Date> parserDate(Date date) {
        List<Date> dates = Lists.newArrayList();

        return dates;
    }
}
